package org.example.api;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.SneakyThrows;

import java.util.HashMap;
import java.util.Map;
/**
 * @author: Li Qing
 * @date: 2024/5/10 11:20
 * @description:
 */
public class ChatGptUtil {

    @SneakyThrows
    public static String inquire(String prompt) {
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("Content-Type", "application/json;charset=UTF-8");
        JSONObject json = new JSONObject();
        //选择模型
        json.set("model", "gpt-3.5-turbo");
        //添加我们需要输入的内容
        JSONArray array = new JSONArray();
        JSONObject json1 = new JSONObject();
        json1.put("role", "system");
        json1.put("content", prompt);
        array.add(json1);
        json.set("messages", array);
        System.out.println(JSONUtil.toJsonStr(json));
        HttpResponse response = HttpRequest.post("https://free.gpt.ge/v1/chat/completions")
                .headerMap(headers, false)
                .bearerAuth("你的key")
                .body(JSONUtil.toJsonStr(json))
                .timeout(5 * 60 * 1000)
                .execute();
        JSONObject jsonObject = JSONUtil.parseObj(response.body());
        JSONArray jsonArray = jsonObject.getJSONArray("choices");
        String string = jsonArray.getJSONObject(0).getJSONObject("message").getStr("content");
        return string;
    }
}
